package com.wzt.lianfirecontrol.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.wzt.lianfirecontrol.bean.ConstData;
import com.xh.common.thread.AsyncExecutor;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.CLIPBOARD_SERVICE;

public class Utils {
    /**
     * 版本名
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 版本号
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        }
        catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 隐藏输入键盘
     * @param view
     * @param context
     */
    public static void hideSoftInput(EditText view, Context context) {
        InputMethodManager inputMeMana = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMeMana.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示软键盘
     */
    public static void showSoftInput(Context context) {
        InputMethodManager inputMeMana = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMeMana.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 根据手机分辨率从dp转成px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率�?px(像素) 的单�?转成�?dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale（DisplayMetrics类中属�?scaledDensity�?
     * @return
     */
    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param fontScale（DisplayMetrics类中属�?scaledDensity�?
     * @return
     */
    public static int sp2px(float spValue, float fontScale) {
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 复制到剪切板
     * @param copyStr 复制内容
     * @param copyTip 提示内容
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public static void copyToClipBoard(Activity activity, String copyStr, String copyTip) {
        if (Build.VERSION.SDK_INT < 11) {
            return;
        }

        if (!StringUtils.isEmpty(copyStr)) {
            ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(CLIPBOARD_SERVICE);
            clipboard.setText(copyStr);
            if (!StringUtils.isEmpty(copyTip)) {
                Toast.makeText(activity, copyTip, Toast.LENGTH_LONG).show();
            }
        }
    }


    /**
     * 根据包名判断apk是否已安装
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }

        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> pName = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                if((pinfo.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)==0) {
                    //如果非系统应用，则添加至appList
                    String pn = pinfo.get(i).packageName;
                    pName.add(pn);
                }
            }
        }
        //判断pName中是否有目标程序的包名，有TRUE，没有FALSE
        return pName.contains(packageName);
    }

    public static String md5(List<String> params) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : params) {
            stringBuffer.append(str);
        }
        try {
            byte[] intputBytes = stringBuffer.toString().getBytes("UTF-8");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hash = md5.digest(intputBytes);
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) hex.append("0");
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }catch (Exception e) {
            return null;
        }
    }

    public static String md5(String content) {
        if (StringUtils.isEmpty(content)){
            return "";
        }
        try {
            byte[] intputBytes = content.getBytes("UTF-8");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hash = md5.digest(intputBytes);
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) hex.append("0");
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断是否存在可用网络
     */
    public static boolean hasNetwork(Context context) {
        android.net.ConnectivityManager cManager = (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo info = cManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 判断sdcard是否可用
     * @return true为可用，否则为不可用
     */
    public static boolean sdCardIsAvailable() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return true;
    }

    /**
     * 从网络下载图片并保存到指定路径
     * @param imgUrl
     * @param filePath
     */
    public static void downloadImageAndSave(String imgUrl, String filePath) throws Exception{
        URL url;
        InputStream is = null;
        FileOutputStream fos = null;
        HttpURLConnection conn;
        try {
            url = new URL(imgUrl);
            conn = (HttpURLConnection) url.openConnection();
            //判定是否会进行302重定向
            if (302 == conn.getResponseCode()) {
                //如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
                String location = conn.getHeaderField("Location");
                url = new URL(location);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
            }

            if(200 == conn.getResponseCode()){
                is = conn.getInputStream();
                File file = new File(filePath);
                fos = new FileOutputStream(file);
                Utils.copyStream(is, fos);
            }
        }
        catch (Exception e) {
            throw e;
        }
        finally {
            try {
                is.close();
                fos.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 拷贝流
     * @param is
     * @param os
     */
    public static void copyStream(InputStream is, OutputStream os) throws IOException {
        if (is == null || os == null) {
            return;
        }

        BufferedInputStream bufIs;
        boolean shouldClose = false;
        if (is instanceof BufferedInputStream) {
            bufIs = (BufferedInputStream) is;
        }
        else {
            bufIs = new BufferedInputStream(is);
            shouldClose = true;
        }

        int bufLen = 102400;
        byte[] buf = new byte[bufLen];
        int len;
        while (true) {
            len = bufIs.read(buf);
            if (len < 0) {
                break;
            }
            os.write(buf, 0, len);
        }
        if (shouldClose) {
            bufIs.close();
        }
    }

    /**
     * 防止重复点击
     * @return
     */
    public static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 0 < timeD && timeD < 1000) {
            return true;
        }
        return false;
    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 校验密码格式 6-16个字符,不包含空格,必须包含数字,字母两种
     * @param password
     * @return
     */
    public static boolean chechPsIsTrue(String password){
        if (StringUtils.isEmpty(password)){
            return false;
        }
//        if (password.length() < 6 || password.length() > 16){
//            return false;
//        }
//        int pwContainType = 0;
//        String numberRuler = ".*[0-9]+.*";
//        if (password.matches(numberRuler)){
//            pwContainType++;
//        }
//        String strRuler = ".*[a-zA-Z]+.*";
//        if (password.matches(strRuler)){
//            pwContainType++;
//        }
////        String specialRuler = ".*[ _.`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]+.*";
////        if (password.matches(specialRuler)){
////            pwContainType++;
////        }
//        return pwContainType > 1;
        return Pattern.matches("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$", password);
    }

    /**
     * 校验手机号
     * @param phoneNumber
     * @return
     */
    public static boolean checkPhoneNumber(String phoneNumber){
        if (StringUtils.isEmpty(phoneNumber)){
            return false;
        }
        return Pattern.matches("^(1[0-9][0-9])\\d{8}$", phoneNumber);
    }

    /**
     * 校验邮箱
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        if (StringUtils.isEmpty(email)){
            return false;
        }
        return Pattern.matches("^(\\s*)|\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", email);
    }


    /**
     * 翻译设备状态颜色
     * @param statusId
     * @return
     */
    public static String changeStatusIdToStr(String statusId){
        if (StringUtils.isEmpty(statusId)){
            return "";
        }
        // 1报警 2故障 4监管 6屏蔽 98预警
        switch (statusId){
            case "1":
                return "火警";
            case "2":
                return "故障";
            case "4":
                return "监管";
            case "6":
                return "屏蔽";
            case "98":
                return "预警";
        }
        return "";
    }

    /**
     * 翻译设备状态
     * @param statusId
     * @return
     */
    public static String changeStatusIdToColor(String statusId){
        if (StringUtils.isEmpty(statusId)){
            return "";
        }
        // 1报警 2故障 4监管 6屏蔽 98预警
        switch (statusId){
            case "1":
                return "#F03141";
            case "2":
                return "#FFD214";
            case "4":
                return "#FC7D28";
            case "6":
                return "#FC7070";
            case "98":
                return "#A634FE";
        }
        return "#5673FF";
    }


    /**
     * 翻译设备状态
     * @param status
     * @return
     */
    public static String changeStrToStatusId(String status){
        if (StringUtils.isEmpty(status)){
            return "";
        }
        try {
            switch (status){
                case "火警":
                    return "1";
                case "故障":
                    return "2";
                case "监管":
                    return "4";
                case "屏蔽":
                    return "6";
                case "预警":
                    return "98";
            }
        }catch (Exception e){
        }
        return "";


    }

    /**
     * 数字转汉字
     * @param number
     * @return
     */
    public static String convert(int number) {
        String[] single = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};//汉字一到九
        String[] unit = {"", "十", "百", "千", "万", "亿"};//汉字单位
        StringBuilder sb = new StringBuilder();
        int[] unitInt = {100000000, 10000, 1000, 100, 10};
        int m = 0;
        int tmp = -1;
        for (int i : unitInt) {

            int n = number / i;
            number = number % i;
            if (sb.length() != 0 || n != 0) {
                if (n > single.length - 1) {
                    String cc = convert(n);
                    sb.append(cc);
                } else {
                    if (0==tmp && 0==n) {

                    } else {
                        sb.append(single[n]);
                    }

                    tmp = n;
                }
                if (n != 0) {
                    sb.append(unit[unit.length - 1 - m]);
                }

            }
            m++;

        }
        if (number != 0) {
            sb.append(single[number]);
        }
        String ret = sb.toString();
        if (ret.length()==0){
            return "零";
        }
        String last = String.valueOf(ret.charAt(ret.length() - 1));
        if ("零".equals(last)) {
            ret = ret.substring(0, ret.length() - 1);
        }

        return ret;
    }

    /**
     * 栈内是否存在activity
     * @param activity
     * @param context
     * @return
     */
    public static boolean isExistMainActivity(Class<?> activity, Context context) {
        try {
            Intent intent = new Intent(context, activity);
            ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
            boolean flag = false;
            if (cmpName != null) { // 说明系统中存在这个activity    
                ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
                List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);//
                for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                    if (taskInfo.baseActivity.equals(cmpName)) {// 说明它已经启动了
                        flag = true;
                        break;//跳出循环，优化效率
                    }
                }
            }
            return flag;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 清除拍照临时文件
     */
    public static void clearPhotoData(Context context) {
        AsyncExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String photoPath = PreferencesUtils.getString(context, ConstData.PHOTOPATH, "");
                    if (!StringUtils.isEmpty(photoPath)) {
                        String[] paths = photoPath.split(";");
                        for (String path : paths) {
                            File file = new File(path);
                            if (file.isFile() && file.exists()) {
                                file.delete();
                            }
                        }
                    }
                }catch (Exception e){

                }finally {
                    PreferencesUtils.putString(context, ConstData.PHOTOPATH, "");
                }
            }
        });
    }

    public static String getImageUrls(String[] imageUrls){
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < imageUrls.length; i++){
            if (!StringUtils.isEmpty(imageUrls[i])){
                if (!StringUtils.isEmpty(stringBuilder.toString())){
                    stringBuilder.append(",");
                }
                stringBuilder.append(imageUrls[i]);
            }
        }
        return stringBuilder.toString();
    }

    /**
     *
     * @param activity
     */
    public static void openNfc(Activity activity, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
            activity.startActivityForResult(setNfc, requestCode);//5.假如手机的nfc功能没有被打开。则跳到打开nfc功能的界面
        }else {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            activity.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 字节数组转字符串
     * @param inarray
     * @return
     */
    public static String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";
        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    //删除文件夹和文件夹里面的文件
    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }
}
